/**
 * 根据formItems封装多个表单在一起 比如 跳转协议
 * @Author: linzy
 * @Date: 2022-07-27
 * @function useFormTypes
 * @property {string} jump - 跳转类型 默认值： <br />
 *  name: "addrType,addrUrl", <br />
    label: "跳转类型,跳转参数", <br />
    map: ["typeid", "typename"], <br />
    required: true  <br />
 * @property {string} dateRange - 日期范围 默认值： <br />
    name: "startTime,endTime", <br />
    label: "开始时间,结束时间", <br />
    required: [true, false] <br />
 * @property {*} ... - 任何传参需要注意如果是数组必须使用[]包裹！如select组件传入options则必须使用options: [list,]; 建议传参使用数组格式传入；
 * <caption>表单项组合types</caption>
 */
import { useRequest } from "@/hooks";
import { setDefaultAttrs, setMpUrlFormItem } from "@/hooks/tools";
import { message, Button } from "antd";
import moment from "moment";
import * as gConfig from "@/config";
import _ from "lodash";
import * as gApi from "@/api";
/**
 *
 * @param {*} type
 * @returns
 */
function getUnit(type) {
  if (/^date/i.test(type)) {
    return "days";
  } else {
    return type + "s";
  }
}
/**
 * 转化传入的参数，都会转成统一的数组
 * @ignore
 * @param {object} restProps - 传入的restProps
 * @param {number} listLength=2 - 表单项的长度
 * @returns
 */
function getFormItemList(restProps, listLength = 2) {
  var formItemObj = {};
  _.forEach(restProps, (value, key) => {
    if (typeof value === "string") {
      if (/\,/.test(value)) {
        formItemObj[key] = value.split(",");
      } else {
        formItemObj[key] = _.fill(Array(listLength), value);
      }
    } else if (Array.isArray(value)) {
      formItemObj[key] = value;
    } else {
      formItemObj[key] = _.fill(Array(listLength), value);
    }
  });
  // 转成单个对象的格式
  var tempList = [];
  for (let i = 0; i < listLength; i++) {
    tempList.push({});
  }
  _.forEach(formItemObj, (value, key) => {
    _.forEach(value, (item, index) => {
      tempList[index][key] = _.cloneDeep(item);
    });
  });
  return tempList;
}
/**
 * 插入formItems 列表中
 * @ignore
 * @param {array} list - formItem数组
 * @param {number} index - 下标
 * @param {array} formItemDefaultList - 默认的表单数组
 * @param {array} formItemList - 转化过得表单数组
 */
function spliceFormItems({
  list,
  index,
  formItemDefaultList = [],
  formItemList = []
}) {
  var mergeList = formItemDefaultList.map((o, i) => {
    return { ...o, ...formItemList[i] };
  });
  list.splice(index, 1, ...mergeList);
}
// 获取dateRange的type
function getDateType(type) {
  if (_.isString(type)) {
    return type;
  } else if (_.isArray(type)) {
    return type[0];
  } else {
    return type;
  }
}
export default (formItems, form) => {
  const { run: itemDetail, loading: itemDetailLoading } = useRequest(
    gApi.itemDetail
  );
  const { run: liveGet, loading: liveGetLoading } = useRequest(gApi.liveGet);
  formItems.forEach((item, index, list) => {
    let { types, isSearch = false, ...restProps } = item;
    if (types) {
      let formItemList, formItemDefaultList;
      if (types === "jump") {
        restProps = _.omit(restProps, "options");
        setDefaultAttrs(restProps, {
          name: ["addrType", "addrUrl"],
          label: ["跳转类型", "跳转参数"],
          required: [true, true],
          type: ["select", "textarea"]
        });
        formItemList = getFormItemList(restProps, 2);
        formItemDefaultList = [
          {
            map: ["typeid", "typename"],
            options: item.options,
            onChange(val, form) {
              var typeItem = list[index].options?.find(o => o.typeid === val);
              if (typeItem) {
                list[index + 1].placeholder = typeItem?.paramdesc;
              }
              form.setFieldsValue({ [formItemList[1].name]: undefined });
              if (gConfig.addrTypeNoAddrIdList.includes(val)) {
                list[index + 1].required = false;
              } else {
                list[index + 1].required = true;
              }
            }
          },
          {}
        ];
      } else if (types === "checkItemId") {
        setDefaultAttrs(restProps, {
          name: ["itemId", "checkItemTitle"],
          label: ["商品id", "商品标题"],
          required: [true, true],
          disabled: [false, true],
          type: ["inputNumber", "textarea"]
        });
        formItemList = getFormItemList(restProps, 2);
        formItemDefaultList = [
          {
            onChange() {
              form.setFieldsValue({ [formItemList[1].name]: undefined });
            },
            props: {
              suffix: (
                <Button
                  type="primary"
                  loading={itemDetailLoading}
                  onClick={() => {
                    const val = form.getFieldValue(formItemList[0].name);
                    itemDetail(val).then(ret => {
                      if (ret.res) {
                        const { itemStatus, title } = ret.res;
                        if (itemStatus === 2) {
                          form.setFieldsValue({
                            [formItemList[1].name]: title
                          });
                        } else {
                          message.error(
                            `该商品${gConfig.itemStatusObj[itemStatus]},请重新选择`
                          );
                        }
                      }
                    });
                  }}
                >
                  校验
                </Button>
              )
            }
          },
          {
            exclude: true,
            rules: [
              { required: true, message: "商品id校验不通过，请检查是否正确" }
            ]
          }
        ];
      } else if (types === "checkLiveId") {
        setDefaultAttrs(restProps, {
          name: ["liveId", "checkLiveTitle"],
          label: ["直播id", "直播信息"],
          required: [true, true],
          disabled: [false, true],
          type: ["inputNumber", "textarea"]
        });
        formItemList = getFormItemList(restProps, 2);
        formItemDefaultList = [
          {
            onChange() {
              form.setFieldsValue({ [formItemList[1].name]: undefined });
            },
            props: {
              suffix: (
                <Button
                  type="primary"
                  loading={liveGetLoading}
                  onClick={() => {
                    const val = form.getFieldValue(formItemList[0].name);
                    liveGet(val).then(ret => {
                      if (ret.res?.items) {
                        const { status, title, starttm } = ret.res.items[0];
                        if (status === 0) {
                          form.setFieldsValue({
                            [formItemList[1]
                              .name]: `直播标题：${title}\n直播开始时间: ${moment(
                              starttm
                            ).format("YYYY-MM-DD HH:mm:ss")}`
                          });
                        } else {
                          message.error(
                            `该直播${gConfig.liveStatusObj[status]},请重新选择`
                          );
                        }
                      }
                    });
                  }}
                >
                  校验
                </Button>
              )
            }
          },
          {
            exclude: true,
            rules: [
              { required: true, message: "直播id校验不通过，请检查是否正确" }
            ]
          }
        ];
      } else if (types === "mpJump") {
        restProps = _.omit(restProps, "options");
        setDefaultAttrs(restProps, {
          name: ["addrType", "appletAddrType", "addrUrl"],
          label: ["跳转类型", "小程序跳转类型", "跳转参数"],
          required: [false, true, true],
          type: ["select", "select", "textarea"]
        });
        formItemList = getFormItemList(restProps, 3);
        formItemDefaultList = [
          {
            allowClear: false,
            options: [{ label: "匠心小程序", value: 95 }],
            show: false,
            need: true,
            initialValue: 95
          },
          {
            options: item.options || gConfig.mpJumpOptions,
            onChange(val) {
              form.setFieldsValue({ [formItemList[2].name]: "" });
              if (val) {
                setMpUrlFormItem({
                  appletAddrType: val,
                  formItem: list[index + 2]
                });
              }
            }
          },
          {
            encode: true,
            mode: "mpJump",
            need: true
          }
        ];
      } else if (types === "dateRange") {
        setDefaultAttrs(restProps, {
          name: "startTime,endTime",
          label: "开始时间,结束时间",
          required: [true, false],
          disabled: [false, false]
        });
        formItemList = getFormItemList(restProps, 2);
        formItemDefaultList = [
          {
            startOf:
              isSearch && !/datetime/i.test(getDateType(restProps.type))
                ? true
                : false,
            disabledDate: isSearch
              ? false
              : currentData => {
                  let startTime = currentData.startOf(formItemList[0].type);
                  let endTime = form
                    .getFieldValue(formItemList[1].name)
                    ?.startOf(formItemList[0].type);
                  let preTime = moment().subtract(
                    1,
                    getUnit(formItemList[0].type)
                  );
                  return (
                    startTime < preTime || (endTime && startTime > endTime)
                  );
                }
          },
          {
            endOf:
              isSearch && !/datetime/i.test(getDateType(restProps.type))
                ? true
                : false,
            disabledDate: isSearch
              ? false
              : currentData => {
                  let endTime = currentData.startOf(formItemList[0].type);
                  let startTime = form
                    .getFieldValue(formItemList[0].name)
                    ?.startOf(formItemList[0].type);
                  let preTime = moment().subtract(
                    1,
                    getUnit(formItemList[0].type)
                  );
                  return (
                    endTime < preTime || (startTime && startTime > endTime)
                  );
                }
          }
        ];
      }
      spliceFormItems({ list, index, formItemDefaultList, formItemList });
    }
  });
  return formItems;
};
